<template>
  <h1>修改用户</h1>
  <div>
    <el-form ref="ruleFormRef" style="width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="用户名" prop="userName" @change="OneUserName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
      <el-form-item label="性别" prop="name">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio :value="false">男</el-radio>
          <el-radio :value="true">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="所在地址" prop="name">
        <el-select v-model="ruleForm.provinceId" @change="GetGetCity(ruleForm.provinceId)"
          style="width: 150px;margin-right: 20px;" placeholder="请选择省份">
          <el-option v-for="items in objProvince" :label="items.provinceName" :value="items.provinceId" />
        </el-select>
        <el-select v-model="ruleForm.cityId" @change="GetCounty(ruleForm.cityId)"
          style="width: 150px;margin-right: 20px;" placeholder="请选择市">
          <el-option v-for="items in objGetCity" :label="items.cityName" :value="items.cityId" />
        </el-select>
        <el-select v-model="ruleForm.countyId" style="width: 150px;" placeholder="请选择县">
          <el-option v-for="items in objCounty" :label="items.countyName" :value="items.countyId" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="所在地址" prop="name">
        <el-cascader size="large" :options="options" v-model="provinces" @change="handleChange"
          placeholder="请选择省市区"></el-cascader>
      </el-form-item>

      <el-form-item label="详细地址" prop="hamletName">
        <el-input v-model="ruleForm.hamletName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          修改
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import { regionData } from "element-china-area-data";//引入
import { el } from 'element-plus/es/locales.mjs';


const store = useCounterStore();
const router = useRouter();
const route = useRoute();
const options = regionData;
//省市县储存
let provinces: any = ref([]);

// console.log(options);

//姓名唯一验证状态
const Status = reactive({
  OneNameStatu: 1, //1通过名不称重复 2不通过名称重复
})

//反填User数据
const FanTian = () => {
  axios.get(`https://localhost:7174/api/Message/FanTianUser?UserId=` + store.ccstore.UpdateUserId).then(res => {
    console.log(res.data.data)
    ruleForm.userId = store.ccstore.UpdateUserId
    ruleForm.userName = res.data.data.userName
    ruleForm.sex = res.data.data.sex
    ruleForm.provinceId = res.data.data.provinceId
    ruleForm.cityId = res.data.data.cityId
    ruleForm.countyId = res.data.data.countyId
    ruleForm.hamletName = res.data.data.hamletName
    ruleForm.updateName = store.ccstore.nickName
    ruleForm.updateTime = new Date()
    getAdder(ruleForm.provinceId, ruleForm.cityId, ruleForm.countyId)
  })
}

//三级联动反填
const getAdder = (id1: string, id2: string, id3: string) => {
  provinces.value = [id1.toString(), id2.toString(), id3.toString()]
  console.log(provinces)
}

//#region 后端获取省市县数据
//获取省份
const objProvince: any = ref([]);
const GetProvince = () => {
  axios.get("https://localhost:7174/api/Message/GetProvince", {}).then(res => {
    objProvince.value = res.data.data
  })
}

//获取市
const objGetCity: any = ref([]);
const GetGetCity = (ids: any) => {
  ruleForm.cityId = ""
  axios.get("https://localhost:7174/api/Message/GetCity", {
    params: {
      ProvinceId: ids,
    }
  }).then(res => {
    objGetCity.value = res.data.data
  })
}

//获取县
const objCounty: any = ref([]);
const GetCounty = (ids: any) => {
  ruleForm.countyId = "";
  axios.get("https://localhost:7174/api/Message/GetCounty", {
    params: {
      CityId: ids,
    }
  }).then(res => {
    objCounty.value = res.data.data
  })
}

//#endregion


//#region 添加功能

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()


const handleChange = (values: any) => {
  provinces = values
  ruleForm.provinceId = values[0]
  ruleForm.cityId = values[1]
  ruleForm.countyId = values[2]
}

//传User参数
const ruleForm: any = reactive({
  "userId": 1,
  "userName": "",
  "password": "12345678",
  "nickName": "",
  "sex": true,
  "provinceId": 0,
  "cityId": 0,
  "countyId": 0,
  "hamletName": "",
  // "createName": "",
  // "createTime": "",
  "updateName": "",
  "updateTime": "",
  "isDel": false
})


const rules = reactive<FormRules>({
  userName: [
    { required: true, message: '用户名不可为空', trigger: 'blur' },
  ],
  hamletName: [
    { required: true, message: '详细地址不可为空', trigger: 'blur' },
  ],
})

//姓名唯一验证
const OneUserName = () => {
  axios.get("https://localhost:7174/api/Message/OneUserName", {
    params: {
      UserName: ruleForm.userName
    }
  }).then(res => {
    // console.log(res.data.code, "唯一验证状态码")
    if (res.data.code == 209) {
      ElMessage.error(res.data.msg)
      return Status.OneNameStatu = 2;
    } else {
      ElMessage.success(res.data.msg)
      return Status.OneNameStatu = 1;
    }
  })
}

//修改
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (Status.OneNameStatu == 2) {
        ElMessage.error("添加失败!!用户名称重复")
        return;
      }
      axios.post("https://localhost:7272/api/Message/UpdateUser", ruleForm).then(res => {
        console.log(res)
        if (res.data.code == 206) {
          ElMessage.success(res.data.msg);
          router.push({
            name: 'UserList'
          })
        }
        else {
          ElMessage.error(res.data.msg);
        }
      })
    } else {
      // console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//#endregion

onMounted(() => {
  GetProvince();
  FanTian();
})




</script>

<style scoped></style>